package cn.ltpcloud.common.filter;


import cn.ltpcloud.common.constant.HttpStatus;
import cn.ltpcloud.common.entity.AjaxResult;
import cn.ltpcloud.common.pojo.auth.LoginUser;
import cn.ltpcloud.common.runner.AnonymousRunner;
import cn.ltpcloud.common.utils.JWTUtils;
import cn.ltpcloud.common.utils.JsonUtils;
import cn.ltpcloud.common.utils.RedisUtils;
import cn.ltpcloud.common.utils.ReqUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static cn.ltpcloud.common.utils.ReqUtils.isPathMatching;

/**
 * token认证过滤器
 *
 * @author jiejiebiezheyang
 * @since 2023-04-03 14:05
 */
@Component
public class JWTFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        // 获取token
        String token = request.getHeader("Authorization");
        String requestURI = request.getRequestURI();
        // 需要放行的端口直接放行
        if (isPathMatching(AnonymousRunner.ANONYMOUS, requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token,获取userId
        String userId = null;
        try {
            userId = JWTUtils.parseToken(token, "userId", false);
        } catch (Exception e) {
            response.getWriter().println(JsonUtils.toJsonStr(AjaxResult.error(HttpStatus.UNAUTHORIZED, e.getMessage())));
            return;
        }
        // 从redis中获取用户信息
        LoginUser loginUser = redisUtils.getCacheObject("login:" + userId);
        if (loginUser == null || loginUser.getSysUser() == null) {
            response.getWriter().println(JsonUtils.toJsonStr(AjaxResult.error(HttpStatus.FORBIDDEN, "Session Expiration")));
            return;
        }
        ReqUtils.getRequest().setAttribute("userId", userId);
        // 将用户信息存入SecurityContext
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}